function PurchaseAdd_Code(id,from,type) {  
	var date=new Date();
	var hidden1="";
	var hidden2="hidden";
	if(id!=0)
	{
		var hidden1="hidden";
		var hidden2="";
	}
	var buffer = new StringBuffer();
	buffer.append('<div id="purchaseid" class="crmsheet border-bottom" val="'+id+'" from="'+from+'" type="'+type+'"><div class="ctitle"><div class="cname">采购单号</div><div class="require">*</div></div><div class="ctext"><input id="txt_num" type="text" placeholder="" readonly="readonly" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div id="supplier" class="crmsheet border-bottom"><div class="ctitle"><div class="cname">供&nbsp; 应&nbsp; 商</div><div class="require">*</div></div><div class="ctext"><input id="txt_supplierid" supplierid="0" type="text" placeholder="选择供应商" readonly="readonly" value=""/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom date"><div class="ctitle"><div class="cname">采购日期</div><div class="require">*</div></div><div class="ctext"><input id="txt_buydate" type="text" placeholder="选择采购日期" readonly="readonly" value="'+date.Format("yyyy-MM-dd")+'"/></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	buffer.append('<div class="crmsheet border-bottom" style="height:120px;"><div class="ctitle"><div class="cname">备注</div></div><textarea id="txt_bak" placeholder="填写订单备注" onfocus="ScrollTop()"></textarea></div>');
	buffer.append('<div id="product_tool" class="pline border-bottom"><font style="padding-left:10px;" class="'+hidden1+'">选择产品</font><table class="'+hidden2+'"><tr><td width="20%" >产品名称</td><td width="20%" >选择仓库</td><td width="10%">单位</td><td width="15%">价格</td><td width="10%">数量</td><td width="10%">折扣</td><td width="15%">总金额</td></tr></table></div>');
	buffer.append('<div id="product_panel"><table id="porderdetail"></table></div>');
	buffer.append('<div id="add_product" class="add_product"><img src="img/add.png"/></div>');
	buffer.append('<div id="candelete" class="loading hidden" style="height:14px; margin-top:10px; margin-bottom:30px; float:left;">长按产品名称可以删除哦</div>');
	return buffer.toString();
};

var map;
var wsub;
var count=0;
var myScroll3;
function Init_PurchaseAdd(){
	var purchaseid=$("#purchaseid").attr("val");
	var customer;
	if(purchaseid!=0)
	{
		var data = {};
		data.act = "One_Purchase";
		data.id=purchaseid;
		data.source=source;
		data.userid=userid;
		data.comid=comid;
		data.sign=GetSign(data.act);
		mui.getJSON(crm_domain, data, function (json) {
	            if (json.state) {
	                purchase=json.data.purchase;
	                $("#txt_num").val(purchase.Num);
	                $("#txt_supplierid").val(purchase.SupplierName).attr("supplierid",purchase.SupplierID);
	                $("#txt_buydate").val(purchase.BuyDate.ToDate());
	                $("#txt_bak").val(purchase.Bak);
	                Init_PurchaseProduct(json.data.purchasedetail);
	            } else {
					plus.nativeUI.toast(json.msg);
	            }
	    });
    }
	else{
		var data = {};
		data.act = "Table_Num";
		data.flag="purchase";
		data.type=$("#purchaseid").attr("type");
		data.comid=comid;
		data.sign=GetSign(data.act);
		mui.getJSON(crm_domain, data, function (json) {
	            if (json.state) {
	                $("#txt_num").val(json.data);
	            }
	    });
	}
	get("supplier").addEventListener("tap",function(){
		myScroll3 = OpenScroll2(4,"选择供应商","",function(pageindex){
										Receive_SupplierSelect(pageindex);
								},function(){
									
								},SupplierSelect_Code(),70);
								//$("#contentlist2").append(Publish_Code());
								Receive_SupplierSelect(1);
								get("find2").addEventListener("tap",function(){
				      				$("#searchicon2").hide();
	      							$("#searchicons2").show();
	      							$("#keyword2").attr("placeholder","供应商名字，地址");
			    					if($("keyword2").val()!="")
			    					{
			    						//WorkMate_Search();
			    					}
				      			});
	});
	
	get("add_product").addEventListener("tap",function(){
	    	myScroll3 = OpenScroll2(4,"选择产品","",function(pageindex){
										Receive_ProductSelect(pageindex);
								},function(){
									
								},ProductSelect_Code("purchase"),70);
								Receive_ProductSelect(1);
								get("find2").addEventListener("tap",function(){
				      				$("#searchicon2").hide();
	      							$("#searchicons2").show();
	      							$("#keyword2").attr("placeholder","产品名称，编号");
			    					if($("keyword2").val()!="")
			    					{
			    						//WorkMate_Search();
			    					}
				      			});
	    });
	mui(".divmsg").on("tap",".date",function(){
			obj10=this;
			var t=new Date();
			if($(this).find("input").val()!="")
			{
				var year_month_day=$(this).find("input").val().split("-");
				t.setFullYear(year_month_day[0]);
				t.setMonth(year_month_day[1]-1);
				t.setDate(year_month_day[2]);
			}
			plus.nativeUI.pickDate( function(e){
				var d=e.date;
				$(obj10).find("input").val((d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()).ToDate());
			},function(e){
				console.log( "未选择日期："+e.message );
			},{date:t});
		});
};

function Init_PurchaseProduct(orderdetail){
	var data = {};
			data.act = "Init_Library_Dialog";
			data.source=source;
			data.userid=userid;
			data.comid=comid;
			data.sign=GetSign(data.act);
			var str="";
			mui.getJSON(crm_domain, data, function (json) {
		            if (json.state) {
		            	$.each(json.data, function(i,info) {
		            		str+='<option value="'+info.ID+'">'+info.Name+'</option>';
		            	});
		            	
		            	$.each(orderdetail,function(i,info){
								$("#product_panel table").append('<tr id="'+info.ProductID+'"><td width="20%" >'+info.ProductName+'</td><td width="20%"><select>'+str+'</select></td><td width="10%">'+info.Unit+'</td><td width="15%"><div style="width:50px; height:100%; margin:0 auto;" class="ui-border-radius"><input type="text" value="'+info.BuyPrice+'" onkeyup="Check_Money(this);Cal_Purchase(this)" style="width:50px;" onfocus="ScrollTop()"/></div></td><td width="10%"><div style="width:30px; height:100%; margin:0 auto;" class="ui-border-radius"><input type="text" value="'+info.Count+'" onkeyup="Check_Money(this);Cal_Purchase(this)" style="width:30px;" onfocus="ScrollTop()"/></div></td><td width="10%"><div style="width:30px; height:100%; margin:0 auto;" class="ui-border-radius"><input type="text" value="'+info.Percent+'" onkeyup="Check_Money(this);Cal_Purchase(this)" style="width:30px;" onfocus="ScrollTop()"/></div></td><td width="15%">'+info.AllMoney.toFixed(2)+'</td></tr>');
								$("#product_panel table tr:last select").val(info.LibraryID);
						});
		            }
		            
		   });
	
	
};


function Save_Purchase() {
    var data = {};
        data.act = "Save_Purchase";
        data.userid=userid;
		data.comid=comid;
        data.id = $("#purchaseid").attr("val");
        data.num = $("#txt_num").val();
        data.supplierid = $("#txt_supplierid").attr("supplierid");
        data.buydate = $("#txt_buydate").val();
        data.bak = $("#txt_bak").val();
        data.source = source;
        data.version = version;
        data.count = 0;
        data.allmoney = 0;
        data.type=$("#purchaseid").attr("type");
        var purchasedetail = new Array();
        var error = false;
        if (data.supplierid=="0") {
            plus.nativeUI.toast("请选择供应商");
            return;
        }
        if (data.buydate.Trim()== "") {
            plus.nativeUI.toast("请选择采购日期"); 
            return;
        }
        $("#product_panel tr").each(function (i, row) {
            var detail = "";
                var input = $(row);
                detail += input.attr("id") + "_"; //拼接产品id
                input = $(row).find("td:eq(1)").find("select");
                if (input.val()=="" || input.val()==null) {
                    plus.nativeUI.toast("请选择仓库");
                    error = true;
                    return true;
                }
                detail += input.val() + "_"; //拼接仓库id
                input = $(row).find("td:eq(2)");
                detail += input.html() + "_"; //拼接计量单位
                input = $(row).find("td:eq(3) input");
                if (input.val().Trim()=="" || input.val().Trim()=="0") {
                    plus.nativeUI.toast("请填写价格");
                    input.focus();
                    error = true;
                    return true;
                }
                var costprice = parseFloat(input.val());
                detail += costprice + "_"; //拼接价格
                input = $(row).find("td:eq(4) input");
                if (input.val().Trim()=="" || input.val().Trim()=="0") {
                    plus.nativeUI.toast("请填写数量");
                    input.focus();
                    error = true;
                    return true;
                }
                var count = parseInt(input.val());
                detail += input.val() + "_"; //拼接数量
                input = $(row).find("td:eq(5) input");
                if (input.val().Trim()=="" || input.val().Trim()=="0") {
                    plus.nativeUI.toast("请填写折扣");
                    input.focus();
                    error = true;
                    return true;
                }
                var percent = parseFloat(input.val());
                detail += input.val() + "_"; //拼接折扣
                detail += (costprice * count * percent / 100).toFixed(2); //拼接总金额
                data.count += count;
                data.allmoney += costprice * count * percent / 100;
                purchasedetail.push(detail);
            
        });
        if (error) {
            return false;
        }
        
        data.purchasedetail = purchasedetail + "";
        if(data.purchasedetail=="")
        {
        	plus.nativeUI.toast("请选择产品");
        	return;
        }
        
        var trs=$("#product_panel table tr");
        var count=0;
        $.each(trs,function(i,info){
        	var productid1=$(info).attr("id");
        	var libraryid1=$(info).find("select").val();
        	count=0;
        	$.each(trs,function(k,io){
        		var productid2=$(io).attr("id");
        		var libraryid2=$(io).find("select").val();
        		if(productid1==productid2 && libraryid1==libraryid2)
        		{
        			count++;
        			if(count==2)
        			{
        				plus.nativeUI.toast("【"+$(info).find("td")[0].innerHTML+"】存在重复项，请删除一项再保存");
        				return false;
        			}
        		}
        	});
        	if(count>=2)
        	{
        		return false;
        	}
        });
        if(count>=2)
        {
        	return false;
        }
        data.sign=GetSign(data.act);
		plus.nativeUI.showWaiting( "正在保存..." );
        
		mui.getJSON(crm_domain, data, function (json) {
			plus.nativeUI.closeWaiting();
			plus.nativeUI.toast(json.msg);
            if (json.state) {
                CloseWindow();
                if(data.id==0)
                {
                	if($("#purchaseid").attr("from")=="inventory")
                	{
                		Clear_Form();
                		Inventory_Search();
                	}else
                	{
                		$("#divmsg400 input[type='text']").val("").attr("touserid","");
						$("#divmsg400 select").val("");
						$($("#divmsg400 input[type='radio'][value="+$("#purchaseid").attr("type")+"]")).prop("checked", true); 
                		Purchase_Search();
                	}
                }else{
                	Init_PurchaseDetail();
                	obj.find(".orderprice").html("总额："+data.allmoney.toFixed(2));
                }
            } 
        });
};



//计算采购单价格
function Cal_Purchase(o) {
    var tr = $(o).parent().parent().parent();
    var costprice = tr.find("td:eq(3)").find("input").val();
    var count = tr.find("td:eq(4)").find("input").val();
    var percent = tr.find("td:eq(5)").find("input").val();
    tr.find("td:eq(6)").html((parseFloat(costprice * count * percent)/100).toFixed(2));

    //合计
    /*
    var allprice = 0;
    tr.parent().find("tr:gt(0)").each(function (i, row) {
        if ($(row).find("td:eq(1) input").attr("itemid") > 0) {
            allprice += parseFloat($(row).find("td:eq(7)").html());
        }
    });
    $(".purchase_allprice font").html(allprice.toFixed(2) + "元");
    */
};